import { createRouter, createWebHistory } from 'vue-router';
import { ref } from 'vue';
import axios, { AxiosError } from 'axios'; // 导入 Axios 和 AxiosError
import { ElMessage } from 'element-plus';
import { API_BASE_URL } from '@/config.ts';

// 路由组件导入
import WebCode from '@/components/WebCode/WebCode.vue';
import Problem from '@/components/ProblemLib/Promblem.vue';
import UploadCode from '@/components/Manager/UploadCode.vue';
import UploadProblem from '@/components/Manager/UploadProblem.vue';
import UploadTestGroup from '@/components/Manager/UploadTestGroup.vue';
import Manager from '@/components/Manager/Manager.vue';
import ProblemDetail from '@/components/ProblemLib/ProblemDetail.vue';
import Contest from "@/components/contest/Contest.vue";
import Commit from "@/components/ProblemLib/Commit.vue";
import CommitResult from "@/components/ProblemLib/CommitResult.vue";
import Answer from "@/components/ProblemLib/Answer.vue";
import Token from "@/components/login/Token.vue";
import Login from "@/components/login/Login.vue";
import GenerateTestGroup from "@/components/testGroup/GenerateTestGroup.vue";

// 路由实例
const router = createRouter({
    history: createWebHistory(),
    routes: [
        { path: '/WebCode', component: WebCode },
        { path: '/token', component: Token },
        { path: '/Problem', component: Problem },
        { path: '/UploadProblem', component: UploadProblem },
        { path: '/UploadCode', component: UploadCode },
        { path: '/UploadTestGroup', component: UploadTestGroup },
        { path: '/generateTestGroup', component: GenerateTestGroup },
        { path: '/Manager', component: Manager },
        { path: '/problem-detail/:id', name: 'ProblemDetail', component: ProblemDetail },
        { path: '/Contest', component: Contest },
        { path: '/Commit/:id', component: Commit },
        { path: '/Answer/:id', component: Answer },
        { path: '/login', component: Login, meta: { requiresAuth: false } }, // 不需要认证
        { path: '/CommitResult/:id', name: 'CommitResult', component: CommitResult, props: true },
    ],
});

// 检查 Token 是否有效
const checkToken = async () => {
    const token = localStorage.getItem('token');
    console.log('Local Token:', token); // 打印本地存储的 token
    if (!token) {
        console.error('No token found in localStorage');
        return false; // 没有 Token，直接返回无效
    }
    try {
        const response = await axios.get(`${API_BASE_URL}/User/confirmToken`, {
            headers: { token }
        });
        console.log('Confirm Token Response:', response); // 打印验证结果
        if (response.data.code === 0) {
            return true; // Token 有效
        } else {
            handleInvalidToken(response.data.msg);
            return false; // Token 无效
        }
    } catch (error) {
        if (axios.isAxiosError(error)) {
            if (error.response?.status === 401) {
                handleInvalidToken('Token 已过期');
            } else {
                console.error('Token 验证失败:', error);
                ElMessage.error(error.response?.data?.msg || '网络连接异常，请检查后重试');
            }
        } else {
            console.error('未知错误:', error);
            ElMessage.error('发生未知错误，请稍后再试');
        }
        return false; // Token 无效
    }
};

// 处理无效 Token
const handleInvalidToken = (message: string) => {
    localStorage.removeItem('token'); // 清除无效 Token
    ElMessage.error(`${message}，请重新登录`);
};

// 定时检查 Token 的有效性
let tokenCheckInterval: NodeJS.Timeout | null = null;

const startTokenCheck = () => {
    if (tokenCheckInterval) return; // 防止重复启动定时器
    tokenCheckInterval = setInterval(async () => {
        const isValid = await checkToken();
        if (!isValid) {
            clearInterval(tokenCheckInterval!); // 停止定时器
            tokenCheckInterval = null;
            await router.push('/login'); // 跳转到登录页
        }
    }, 3000); // 每 3 秒检查一次
};

const stopTokenCheck = () => {
    if (tokenCheckInterval) {
        clearInterval(tokenCheckInterval);
        tokenCheckInterval = null;
    }
};

// 路由守卫
router.beforeEach(async (to, _, next) => {
    const isPublicRoute = to.meta.requiresAuth === false; // 判断是否为公开路由

    if (isPublicRoute) {
        stopTokenCheck(); // 在公开路由中停止定时检查
        next(); // 公开路由直接放行
    } else {
        const isValid = await checkToken(); // 检查 Token 是否有效
        if (isValid) {
            startTokenCheck(); // 启动定时检查
            next(); // Token 有效，允许访问
        } else {
            stopTokenCheck(); // 停止定时检查
            next({ path: '/login', query: { redirect: to.fullPath } }); // Token 无效，重定向到登录页
        }
    }
});

export default router;